<div class="layui-card layadmin-header" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">主页</a>
        <a>应用管理</a>
        <a><cite>编辑应用</cite></a>
    </div>
</div>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">编辑应用</li>
            </ul>
            <div class="layui-tab-content">
                <style>
                    .center {
                        width: 45%;
                    }
                </style>
                <form class="layui-form center">
                    <div class="layui-form-item">
                        <label class="layui-form-label">产品名称</label>
                        <div class="layui-col-md6">
                            <select id="selectElement" lay-filter="selectFilter" name="productName">
                                <option value="">请选择</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商户分类</label>
                        <div class="layui-input-block">
                            <input type="checkbox" name="shfl1" title="admin" lay-skin="tag" lay-filter="category">
                            <input type="checkbox" name="shfl2" title="测试商户" lay-skin="tag" lay-filter="category">
                            <input type="checkbox" name="shfl3" title="未分类" lay-skin="tag" lay-filter="category">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div>
                            <label class="layui-form-label">商户(多选)</label>
                        </div>
                        <div class="layui-input-inline">
                            <div id="commercialOwner" style="width:200px"></div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商户费率(%)</label>
                        <div class="layui-input-block">
                            <input type="text" required name="mchRate" lay-verify="required"
                                   placeholder="请输入商户费率,留空则不变原有得费率" autocomplete="off"
                                   class="layui-input appName">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">接口模式</label>
                        <div class="layui-input-block">
                            <input type="radio" name="ifMode" lay-filter="demo-radio-filter" checked value="1"
                                   title="单独">
                            <input type="radio" name="ifMode" lay-filter="demo-radio-filter" value="2" title="轮询">
                        </div>
                    </div>
                    <div class="layui-form-item" id="selectElementa_leixing_p" style="display: none">
                        <label class="layui-form-label">接口类型</label>
                        <div class="layui-input-block">
                            <div id="selectElementa_leixing" style="width: 400px">
                                <select id="ifTypeCode" name="jklx">
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" style="display: none" id="selectElementa_p">
                        <label class="layui-form-label">支付通道</label>
                        <div class="layui-input-block">
                            <div id="selectElementa" style="width: 1000px"></div>
                        </div>
                    </div>
                    <div class="layui-form-item" id="selectElementa_default_p">
                        <label class="layui-form-label">支付通道</label>
                        <div class="layui-input-block">
                            <div id="selectElementa_default" style="width: 400px">
                                <select id="payPassageId" name="payPassageId">
                                    <option value="">请选择</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" id="selectElement_p">
                        <label class="layui-form-label">支付子通道</label>
                        <div class="layui-col-md6">
                            <select id="selectElementaa" name="zfztd">
                                <option value="">请选择</option>
                                <option value="1">模拟1</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-form-item" id="handle_p">
                        <label class="layui-form-label">操作</label>
                        <div class="layui-input-block">
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">风控</button>
                            <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">测试</button>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-form">
                            <input type="radio" name="AAA" value="1" title="开启">
                            <input type="radio" name="AAA" value="0" title="关闭" checked>
                        </div>
                    </div>
                    <div class="layui-form-item ">
                        <div class="layui-input-block">
                            <button type="button" lay-filter="btnM" lay-submit class="layui-btn ">保存</button>
                            <a class="layui-btn" lay-href="merchant/list/">返回</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script>
    layui.use(['admin', 'form', 'element', 'xmSelect', 'table'], function () {
        var form = layui.form
            , $ = layui.$
            , admin = layui.admin
            , layer = layui.layer
            , element = layui.element
            , xmSelect = layui.xmSelect;
        var responseData = []; //记录选择的数据
        var tableData = []; // 初始为空数组
        element.render('breadcrumb', 'breadcrumb');//渲染导航信息
        // 模拟数据
        function fetchData(url) {
            return new Promise(function (resolve, reject) {
                admin.req({
                    type: 'get',
                    url: layui.setter.baseUrl + url,
                    success: resolve,
                    error: reject
                });
            });
        }

        async function fetchData(url, data) {
            try {
                const response = await new Promise(function (resolve, reject) {
                    admin.req({
                        type: 'get',
                        url: layui.setter.baseUrl + url,
                        data: data, // 将data作为请求参数传递
                        success: resolve,
                        error: reject
                    });
                });
                return response;
            } catch (error) {
                throw new Error('请求出错');
            }
        }

        function renderDropdownOptions(data, elementId) {
            var Element = document.getElementById(elementId);
            for (var i = 0; i < data.length; i++) {
                var option = document.createElement('option');
                option.value = data[i].id;

                option.text = '[' + data[i].id + ']' + data[i].productName; // 展示的话,修改这一行
                Element.appendChild(option);
            }
            form.render();
        }

        // 查询方法
        async function fetchAllData() {
            try {
                const [productRes, mchRes] = await Promise.all([
                    fetchData('/config/pay_product/list'),
                    fetchData('/mch_info/list'),
                ]);
                if (productRes.code === 0) {
                    renderDropdownOptions(productRes.data, 'selectElement');

                } else {
                    layer.alert(productRes.msg, {title: '请求失败'});
                }
                if (mchRes.code === 0) {

                    for (var i = 0; i < mchRes.data.length; i++) {
                        var item = {
                            name: mchRes.data[i].name,
                            value: mchRes.data[i].mchId
                        };
                        responseData.push(item);
                    }
                    commercialOwner.update({
                        data: responseData
                    });
                    form.render();
                } else {
                    layer.alert(mchRes.msg, {title: '请求失败'});
                }
            } catch (err) {
                layer.alert(err, {title: 'error'});
            }
        }

        fetchAllData();


        var commercialOwner = xmSelect.render({
            el: '#commercialOwner',
            language: 'zn',
            clickClose: false,
            filterable: true,
            direction: 'down',
            width: 200,
            height: "auto",
            size: 'small',
            left: '200px',
            toolbar: {
                show: true
                ,
                list: ['ALL', 'CLEAR', 'REVERSE']
            },
            tree: {
                show: true,
                showFolderIcon: true,
                showLine: true,
                expandedKeys: true
            },
            model: {
                label: {type: 'text'}
            },
            data: responseData
        })


        // 监听指定 lay-filter 值的复选框勾选事件
        form.on('checkbox(category)', function (data) {
            if (data.elem.name === 'AAA') {
                var selectedData = responseData.filter(function (item) {
                    return item;
                });
                if (data.elem.checked) {
                    commercialOwner.setValue(selectedData.map(function (item) {
                        return item.value;
                    }));
                } else {
                    // 执行AAA复选框取消勾选后的操作
                    commercialOwner.delete(selectedData.map(function (item) {
                        return item.value;
                    }));
                }
            } else if (data.elem.name === 'BBB') {
                var selectedData = responseData.filter(function (item) {
                    return item;
                });
                if (data.elem.checked) {
                    commercialOwner.setValue(selectedData.map(function (item) {
                        return item.value;
                    }));
                } else {
                    // 执行AAA复选框取消勾选后的操作
                    commercialOwner.delete(selectedData.map(function (item) {
                        return item.value;
                    }));
                }
            } else if (data.elem.name === 'CCC') {
                var selectedData = responseData.filter(function (item) {
                    return item;
                });
                if (data.elem.checked) {
                    console.log('AAA复选框被勾选');
                    commercialOwner.setValue(selectedData.map(function (item) {
                        return item.value;
                    }));
                } else {
                    // 执行AAA复选框取消勾选后的操作
                    commercialOwner.delete(selectedData.map(function (item) {
                        return item.value;
                    }));
                }
            }
        });


        //监听提交
        form.on('submit(btnM)', function (data) {
            console.log(data)
            const field = data.field
            field['shfl'] = []
            // 多选
            for(let i=1;i<=3;i++){
                field['shfl'].push(field['shfl'+i])
                delete field['shlx'+i]
            }

            if (field.status == 1) { // 单独
                // 暂时不需要处理
            } else { // 轮询
                field.zftd = formData.tongdao // 拿到轮询选择得id  数组
            }
            console.log(field)
            admin.req({
                type: 'post',
                url: layui.setter.baseUrl + '/app/update', //模拟接口,
                data: field,
                error: function (err) {
                    layer.alert(err.msg, {title: "请求失败"})
                },
                success: function (res) {
                    if (res.code == 0) {
                        layer.alert(res.msg, {title: '保存成功'}, function (index) {
                            layer.close(index);
                            location.hash = '/merchant/app/';
                        });
                    } else {
                        layer.alert(res.msg, {title: '保存失败'})
                    }
                }
            })
            return false;
        });

        var tableContent = tableData.map(function (item) {
            return `
            <tr>
               <td><input type='checkbox'  lay-skin='primary' lay-filter='itemCheckbox'></td>
                 <td>${item.id}</td>
                 <td>${item.passageName}</td>
                 <td>${item.remark}</td>
                  <td>${item.remark}</td>
                   <td>${item.remark}</td>
                   <td>${item.remark}</td>
                   <td>${item.remark}</td>
             </tr>
            `;
        }).join('');


        // 监听 产品名称
        form.on('select(selectFilter)', function (data) {
            if (data.elem[data.elem.selectedIndex].text == '请选择') {
                var tableContent = ''; // 清空表格内容
                var tableElement = document.querySelector('.layui-table tbody');
                tableElement.innerHTML = tableContent;
                return;
            }
            // 切换到轮询的单选按钮
            $("input[name='status'][value='2']").prop("checked", true);
            $('#selectElement_p').css('display', 'none');
            $('#handle_p').css('display', 'none');
            $('#selectElementa_p').css('display', 'block');
            $('#selectElementa_default_p').css('display', 'none');
            $('#selectElementa_leixing_p').css('display', 'block');

            admin.req({
                type: 'post',
                url: layui.setter.baseUrl + '/config/common/pay_interface_type_all',
                error: function (err) {
                    layer.alert(err);
                },
                success: function (res) {
                    if (res.code == 0) {
                        var ifTypeList = res.data;

                        //遍历赋值
                        for (var i in ifTypeList) {
                            $("#ifTypeCode").append('<option value= ' + ifTypeList[i].ifTypeCode + '>' + ifTypeList[i].ifTypeName + '</option>');
                        }
                        $("#ifTypeCode").find('option[value="' + ifTypeCode + '"]').attr('selected', true);
                        form.render('select');
                    }
                }
            });
            form.render('radio');
            //fetchData('/config/pay_product/list', {productId: data.value})
            fetchData('/config/pay_product/poll_get', {productId: data.value})
                .then(function (response) {
                    // 处理返回的数据
                    tableData = response.data;
                    const dom = document.getElementById('selectElementa').getElementsByClassName('xm-tips')[0]
                    dom.innerText != '请选择' ? dom.innerHTML = '请选择' : ''
                    // 检查数据是否为空
                    if (!tableData || tableData.length === 0) {
                        tableContent = ''; // 清空表格内容
                    } else {
                        // 更新表格内容
                        tableContent = tableData
                            .map(function (item) {
                                return `
              <tr>
                <td><input type='checkbox' lay-skin='primary' itemid="${item.id}" lay-filter='itemCheckbox' ></td>
                <td>${item.id}</td>
                <td>${item.passageName}</td>
                <td>${item.remark}</td>
                <td>${item.remark}</td>
                <td>${item.remark}</td>
                <td>${item.remark}</td>
                <td>${item.remark}</td>
                <td>
                     <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">风控</button>
                     <button type="button" class="layui-btn layui-btn-primary layui-btn-sm">测试</button>
                </td>
              </tr>
            `;
                            })
                            .join('');
                    }
                    var tableElement = document.querySelector('.layui-table tbody');
                    tableElement.innerHTML = tableContent;
                    form.render()
                })
                .catch(function (error) {
                    console.error('请求出错:', error);
                });
        });

        form.on('radio(demo-radio-filter)', function (data) {
            var elem = data.elem; // 获得 radio 原始 DOM 对象
            var checked = elem.checked; // 获得 radio 选中状态
            var value = elem.value; // 获得 radio 值  1 单独   2 轮询
            var othis = data.othis; // 获得 radio 元素被替换后的 jQuery 对象
            if (value == 1) {
                // 普通选择
                $('#selectElement_p').css('display', 'block');
                $('#handle_p').css('display', 'block');
                $('#selectElementa_p').css('display', 'none');
                $('#selectElementa_default_p').css('display', 'block');
                $('#selectElementa_leixing_p').css('display', 'none');
                var tableHTMLDefault = `<select id="payPassageId" name="payPassageId">
      <option value="">请选择</option>
      <option value="AAA">选项 A</option>
      <option value="BBB">选项 B</option>
      <option value="CCC">选项 C</option>
    </select>`;
                $('#selectElementa_default').html(tableHTMLDefault)
                form.render()
            }
            if (value == 2) {
                $('#selectElement_p').css('display', 'none');
                $('#handle_p').css('display', 'none');
                $('#selectElementa').css('width', '1000px');
                $('#selectElementa_p').css('display', 'block');
                $('#selectElementa_default_p').css('display', 'none');
                $('#selectElementa_leixing_p').css('display', 'block');

                form.render()
            }
        });
        form.on('checkbox(itemCheckbox)', function (data) {
            var checkboxElem = data.elem;
            var tableData = layui.table.cache.demo; // 获取表格中所有行的数据
            var rowElem = checkboxElem.closest('tr');
            var rowIndex = rowElem.rowIndex; // 获取当前行的索引

            console.log('当前行的索引:', rowIndex);
            var rowData = tableData[rowIndex]; // 获取当前行的数据

            console.log('当前行的数据:', rowData);
            // 其他处理逻辑...
        });
        var tableHTML = `
 <div>
    <table class="layui-table"   lay-filter="demo">
  <thead>
    <tr>
      <th lay-data="{field:'checkbox', width:50, fixed: 'left'}"><input type="checkbox"  lay-filter='itemCheckbox2' lay-skin="primary"></th>
      <th lay-data="{field:'username', width:80}">通道ID</th>
      <th lay-data="{field:'experience', width:50, sort:true}">通道名称</th>
      <th lay-data="{field:'sign', width: 200}">费率</th>
      <th lay-data="{field:'sign', width: 200}">权重(1-9)</th>
      <th lay-data="{field:'sign', width: 200}">风控设置</th>
      <th lay-data="{field:'sign', width: 200}">操作</th>
      <th lay-data="{field:'sign', width: 200}">标识</th>
      <th style="width: 150px" lay-data="{field:'sign', width: 200}">操作</th>
       </tr>
  </thead>
  <tbody>
    ${tableContent}
  </tbody>
</table>
</div>
  `;
        xmSelect.render({
            el: '#selectElementa',
            prop: {
                name: 'username',
                value: 'username',
            },
            content: tableHTML,
            height: 'auto',
        });

        var formData = {
            tongdao: [],
        }

        form.on('checkbox(itemCheckbox)', function (data) {  // 通道选择
            console.log(data)
            var elem = data.elem; // 获得 checkbox 原始 DOM 对象
            var checked = elem.checked; // 获得 checkbox 选中状态
            var value = elem.value; // 获得 checkbox 值
            var othis = data.othis; // 获得 checkbox 元素被替换后的 jQuery 对象
            var itemid = elem.getAttribute('itemid'); // 获取id
            if (checked) {
                formData.tongdao.push(itemid)
            } else {
                const idIndex = formData.tongdao.indexOf(itemid)
                idIndex > -1 && formData.tongdao.splice(idIndex, 1);
            }

            // 更新界面显示
            // selectElementa_p
            var str = [];
            tableData.filter(item => item.id == itemid).filter(item => str.push(item.passageName))
            document.getElementById('selectElementa').getElementsByClassName('xm-tips')[0].innerText = str.join(',') + ','
            console.log(formData.tongdao)
            // layer.msg('checked 状态: '+ elem.checked);
        });
        var tableHTMLDefault = `<select id="payPassageId" name="payPassageId">
      <option value="">请选择</option>
      <option value="AAA">选项 A</option>
      <option value="BBB">选项 B</option>
      <option value="CCC">选项 C</option>
    </select>`;
        $('#selectElementa_default').html(tableHTMLDefault)
    })

</script>

